package rauguelu.programaEventos;


import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class feedTweet extends ListActivity{

	private ArrayList<Tweet> tweets;
	private ProgressDialog progressDialog;
	private int posActual = 1; 
	private boolean loadingMore =false;
	BaseAdapter adapter;
	View footerView;
	
	   //Runnable to load the items
	   private Runnable loadMoreListItems = new Runnable() {
		@Override
		public void run() {
			//Set flag so we cant load new items 2 at the same time
			loadingMore = true;
			//Reset the array that holds the new items
			tweets = new ArrayList<Tweet>();
			//Simulate a delay, delete this on a production environment!
			try { Thread.sleep(1000);
			} catch (InterruptedException e) {}
			//Get 15 new listitems
			tweets = getTweets("FdelosSentidos", ++posActual);
			//Done! now continue on the UI thread
	       		runOnUiThread(returnRes);
		}
	};
	
	//Since we cant update our UI from a thread this Runnable takes care of that!
	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			//Loop thru the new items and add them to the adapter
			if(tweets != null && tweets.size() > 0){
	              		for(int i=0;i < tweets.size();i++)
	              			((LazyAdapter)adapter).add(tweets.get(i));
	          		 }
			else {
				getListView().removeFooterView(footerView);
			}
			//Tell to the adapter that changes have been made, this will cause the list to refresh
	       		((LazyAdapter)adapter).notifyDataSetChanged();
			//Done loading more.
	           		loadingMore = false;
	       	}
	   };
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_tweet);
        TextView enviarTweet = (TextView)findViewById(R.id.enviarTweet);
        //TextView anterioresTweet = (TextView)findViewById(R.id.anterioresTweet);
        TextView mensajeTweet = (TextView)findViewById(R.id.mensajeTweet);

        
        Typeface font = Typeface.createFromAsset(getAssets(), "VSVBPSB.TTF");
        
        enviarTweet.setTypeface(font);
        //anterioresTweet.setTypeface(font);
        mensajeTweet.setTypeface(font);
        

      
       actualizarTweets(posActual);
      
       
       footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_tweet, null, false);
       getListView().addFooterView(footerView);
        
        enviarTweet.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				try{
					Intent intent = new Intent(Intent.ACTION_SEND);
				    intent.putExtra(Intent.EXTRA_TEXT, "@FdelosSentidos ");
				    intent.setType("text/plain");
				    final PackageManager pm = getBaseContext().getPackageManager();
				    final List activityList = pm.queryIntentActivities(intent, 0);
				    boolean encontrada = false;
				        int len =  activityList.size();
				    for (int i = 0; i < len; i++) {
				        final ResolveInfo app = (ResolveInfo) activityList.get(i);
				        if ("com.twitter.android.PostActivity".equals(app.activityInfo.name)) {
				        	encontrada = true;
				            final ActivityInfo activity=app.activityInfo;
				            final ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name);
				            intent=new Intent(Intent.ACTION_SEND);
				            intent.addCategory(Intent.CATEGORY_LAUNCHER);
				            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				            intent.setComponent(name);
				            intent.putExtra(Intent.EXTRA_TEXT, "@FdelosSentidos ");
				            getBaseContext().startActivity(intent);
				            break;
				        }
				    }
				    if(!encontrada)
				    {
				    	 Toast toast2 =
				                 Toast.makeText(getApplicationContext(),
				                		 "No tienes instalado Twitter en tu Android", Toast.LENGTH_SHORT);
				      
				             toast2.setGravity(Gravity.CENTER|Gravity.CENTER,0,0);
				             toast2.show();
				    }
				}
				catch(final ActivityNotFoundException e) {
					 Toast toast2 =
			                 Toast.makeText(getApplicationContext(),
			                		 "No tienes instalado Twitter en tu Android", Toast.LENGTH_SHORT);
			      
			             toast2.setGravity(Gravity.CENTER|Gravity.CENTER,0,0);
			             toast2.show();
				}
			}

		});
    
	
        /*anterioresTweet.setOnClickListener(new View.OnClickListener() {
		public void onClick(View view) {
			 posActual++;
			 actualizarTweets(posActual);
			}		
		});*/
    }

	
    private final Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			if(tweets!=null && tweets.size()>0)
			{
				actualizarListView();
			}
			
	     
	     //Here is where the magic happens
	       getListView().setOnScrollListener(new OnScrollListener(){
	       	//useless here, skip!
	       	@Override
	       	public void onScrollStateChanged(AbsListView view, int scrollState) {}
	       	//dumdumdum
	       	@Override
	       	public void onScroll(AbsListView view, int firstVisibleItem,
	       		int visibleItemCount, int totalItemCount) {
	       		//what is the bottom iten that is visible
	       		int lastInScreen = firstVisibleItem + visibleItemCount;
	       		//is the bottom item visible & not loading more already ? Load more !
	       		if((lastInScreen == totalItemCount) && !(loadingMore)){
	       			Thread thread =  new Thread(null, loadMoreListItems);
	       			thread.start();
		       		}
	       	}
	       });
		        
			progressDialog.dismiss();
        }
    };
    
    // Metodo que actualiza la ListView con las noticias actuales
	private void actualizarListView(){
	 	// Adaptamos las noticias a la celda del ListView
		
		adapter = new LazyAdapter(this, tweets);
	    setListAdapter(adapter);
	}
    
    
    // Metodo para recargar las noticias
    private void actualizarTweets(final int posActual) {
    	// Lanzamos un evento de ProgressDialog para hacer esperar al usuario
    	progressDialog = ProgressDialog.show(feedTweet.this,
    			"", 
				"Cargando comentarios...");
		
    
    	// Lanzamos la hebra para que el ProgressDialog sea visible
		new Thread(new Runnable(){
			public void run() {
				tweets = getTweets("FdelosSentidos", posActual);
				
								
				// Llamamos al progressHandler para que actualice el ListView
				progressHandler.sendEmptyMessage(0);
			}
		}).start();
    	//tweets = getTweets("FdelosSentidos", posActual);
	}
    
    
	/*public class UserItemAdapter extends ArrayAdapter<Tweet> {
		
		Activity context;

		public UserItemAdapter(Context context, int textViewResourceId, ArrayList<Tweet> tweets) {
			super(context, textViewResourceId, tweets);

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			ViewHolder holder;
			
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//				LayoutInflater vi = context.getLayoutInflater();
				v = vi.inflate(R.layout.listitem_tweet, null);
				
				 holder = new ViewHolder();
				 
				 holder.username = (TextView)v.findViewById(R.id.username);
	             holder.message = (TextView)v.findViewById(R.id.message);
	             holder.image = (ImageView)v.findViewById(R.id.avatar);
	             
	             // Establecemos en la vista las referencias a las etiquetas
	                v.setTag(holder);
			}else {
    			holder = (ViewHolder)v.getTag();
    		}

			Tweet tweet = tweets.get(position);
			if (tweet != null) {
//				TextView username = (TextView) v.findViewById(R.id.username);
//				TextView message = (TextView) v.findViewById(R.id.message);
//				ImageView image = (ImageView) v.findViewById(R.id.avatar);
				
				// Establecemos la celda del ListView con los datos correctos
//	            holder.username.setText(tweets.get(position).username);
//	            holder.message.setText(tweets.get(position).message);
//	            holder.image.setImageBitmap(getBitmap(tweets.get(position).image_url));
	            
	          //  holder.descripcion.setText

				if (holder.username != null) {
					holder.username.setText(tweet.username);
				}

				if(holder.message != null) {
					holder.message.setText(tweet.message);
				}
				
				if(holder.image != null) {
					holder.image.setImageBitmap(getBitmap(tweet.image_url));
				}
			}
			return v;
		}
	
	 // Clase estatica para almacenar los elementos que forman una celda del ListView
    
	}*/
	static class ViewHolder {
    	TextView username;
    	TextView message;
    	ImageView image;
    }
	
    
	public Bitmap getBitmap(String bitmapUrl) {
		try {
			URL url = new URL(bitmapUrl);
			return BitmapFactory.decodeStream(url.openConnection() .getInputStream()); 
		}
		catch(Exception ex) {return null;}
	}
	
	public ArrayList<Tweet> getTweets(String searchTerm, int page) {
		String searchUrl = "http://search.twitter.com/search.json?q=@" 
							+ searchTerm + "&rpp=10&page=" + page;
		
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		
		HttpClient client = new  DefaultHttpClient();
		HttpGet get = new HttpGet(searchUrl);
	      
		ResponseHandler<String> responseHandler = new BasicResponseHandler();

		String responseBody = null;
		try{
			responseBody = client.execute(get, responseHandler);
			
			JSONObject jsonObject = null;
			JSONParser parser=new JSONParser();
			
			try {
				Object obj = parser.parse(responseBody);
				jsonObject=(JSONObject)obj;
				
			}catch(Exception ex){
				Log.v("TEST","Exception: " + ex.getMessage());
			}
			
			JSONArray arr = null;
			
			try {
				Object j = jsonObject.get("results");
				arr = (JSONArray)j;
			}catch(Exception ex){
				Log.v("TEST","Exception: " + ex.getMessage());
			}

			for(Object t : arr) {
				Tweet tweet = new Tweet(
						((JSONObject)t).get("from_user").toString(),
						((JSONObject)t).get("text").toString(),
						((JSONObject)t).get("profile_image_url").toString()
						);
				tweets.add(tweet);
			}
		}catch(Exception ex) {
			ex.printStackTrace();
			Toast toast = Toast.makeText(this, "No hay conexi�n", 1);
			toast.show();
		}

		
		
		return tweets;
	}
	
	public class Tweet {
		public String username;
		public String message;
		public String image_url;
		
		public Tweet(String username, String message, String url) {
			this.username = username;
			this.message = message;
			this.image_url = url;
		}
	}
}
	
